<?php 
ob_start();
include('includes/connect.php'); 
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link rel="stylesheet" href="css/style.css" type="text/css" media="screen" title="no title" charset="utf-8" />
<script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script>
</head>

<body>
<?php
	
	$app_id = "203018919739298D";

     $canvas_page = "http://apps.facebook.com/oreosamp/";

     $auth_url = "http://www.facebook.com/dialog/oauth?client_id=" 
            . $app_id . "&redirect_uri=" . urlencode($canvas_page);

     $signed_request = $_REQUEST["signed_request"];

     list($encoded_sig, $payload) = explode('.', $signed_request, 2); 

     $data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);	 	
	
	function array2json($arr) {
		if(function_exists('json_encode')) return json_encode($arr); //Lastest versions of PHP already has this functionality.
		$parts = array();
		$is_list = false;
	
		//Find out if the given array is a numerical array
		$keys = array_keys($arr);
		$max_length = count($arr)-1;
		if(($keys[0] == 0) and ($keys[$max_length] == $max_length)) {//See if the first key is 0 and last key is length - 1
			$is_list = true;
			for($i=0; $i<count($keys); $i++) { //See if each key correspondes to its position
				if($i != $keys[$i]) { //A key fails at position check.
					$is_list = false; //It is an associative array.
					break;
				}
			}
		}
	
		foreach($arr as $key=>$value) {
			if(is_array($value)) { //Custom handling for arrays
				if($is_list) $parts[] = array2json($value); /* :RECURSION: */
				else $parts[] = '"' . $key . '":' . array2json($value); /* :RECURSION: */
			} else {
				$str = '';
				if(!$is_list) $str = '"' . $key . '":';
	
				//Custom handling for multiple data types
				if(is_numeric($value)) $str .= $value; //Numbers
				elseif($value === false) $str .= 'false'; //The booleans
				elseif($value === true) $str .= 'true';
				else $str .= '"' . addslashes($value) . '"'; //All other things
				// :TODO: Is there any more datatype we should be in the lookout for? (Object?)
	
				$parts[] = $str;
			}
		}
		$json = implode(',',$parts);
		
		if($is_list) return '[' . $json . ']';//Return numerical JSON
		return '{' . $json . '}';//Return associative JSON
	} 
	
	try{
		   include_once "facebookLib.php";
		}
		catch(Exception $o){
		   echo '<pre>';
		   var_dump($o);
		   echo '</pre>';
		}
	
		// Create our Application instance.
		$config = array(
			'appId'  => '203018919739298',
			'secret' => 'ebb0bf6fc5affd543b405569706c0878',
			'cookie' => true,
			'status' => true,
			'xfbml' => true,
		);
		
		// Initiate the library	
		$facebook = new facebookLib($config);
		facebookLib::$CURL_OPTS[CURLOPT_CAINFO] = 'ca-bundle.crt';
		$session = $facebook->getSession();
	
	if (!$session) {        
 
            echo("<script> top.location.href='" . $auth_url . "'</script>");
        }
	else
	{
			$facebook->getLoginStatusUrl();
			
			// Session based graph API call.
			if ($facebook->getSession()) {
			try {
			$user_info=($facebook->getInfo());
			
			$json = array2json($user_info);
			//print_r($user_info);
			$firstarray=explode(",",$json);
			$secondarray=explode(':"',$firstarray[0]);
			$thirdarray=explode('"',$secondarray[1]);
	
			if(!isset($_REQUEST['qattno']) || (isset($_REQUEST['qattno']) && $_REQUEST['qattno']<5))
			{
			?>
				<form name="info" id="info" method="post" action="infoshare.php">
				<?php if(!isset($_REQUEST['attempt']))
					{
				?>
			   <input type="hidden" name="user" value="<?php echo $thirdarray[0]; ?>">
				<?php
				$questions=mysql_query('select * from questions order by RAND() limit 1');
				}
				else {
					$questions=mysql_query('select * from questions where qid NOT IN (select qid from test_attempted where uid="'.$_REQUEST['user'].'" and attemt_id="'.$_REQUEST['attno'].'") order by RAND() limit 1');
					$users=mysql_query("select user from user_attempt where uid='".$_REQUEST['user']."'");
					$username=mysql_fetch_array($users);
				?>
				<input type="hidden" name="user" value="<?php echo $username['user']; ?>" />
				<?php
				}
				?>
			   <br /><br />
			   <?php 
							if(!isset($_REQUEST['qattno']))
								{
									$sr="1";
								}
								else
								{
									$sr=$_REQUEST['qattno']+1;
								}
							$i=1;
							$row_count=mysql_num_rows($questions);			
							while($row=mysql_fetch_array($questions)) {
							$que_id=$row["qid"];
							$que=$row["questions"];
							echo '&nbsp;&nbsp;'.$sr.')&nbsp'.'<input type="hidden" name="questions" value="'.$que.'"><input type="hidden" name="questions_id" value="'.$que_id.'">'.$que.'<br><br>'; 
							$sr++;
							$opt=mysql_query("select * from options as o ,questions as q where q.qid=o.qid and q.qid=$que_id"); 
							while($opt_row=mysql_fetch_array($opt))
								{
									$opt_id=$opt_row['opt_id'];
									echo '&nbsp;&nbsp;<input type="radio" name="options1" value="'.$opt_id.'">'.$opt_row['option'].'<br>';
								}							
								$i++;
								} 
							 ?>
							<br />
				<input type="hidden" value="<?php echo $_REQUEST['attempt']; ?>" name="attempts" />
				<input type="submit" value="submit" class="submit">
				</form>	<br /><br />
				<?php if(isset($_REQUEST['attempt']) && $_REQUEST['attempt']=='1')
				{
				?>
				<div><a href="qtq.php">Take QTQ Test</a>&nbsp;&nbsp;<a href="qtp.php">Take Oreo Togetherness Pledge</a></div>		 						 			<?php
				}
				?>
	   <?php
			}
			else
			{
				header('Location:score.php');
			}
	
	} catch (Exception $e) {
	print $e->getMessage();
	}
	}
?>
    <fb:serverFbml style="width: 500px;">
        <script type="text/fbml">
            <fb:fbml>
 
                    <fb:is-logged-out>
                        <fb:else>
                            <fb:request-form content="Join me on foursquare! It's the best way to meetup with friends and discover new places. &lt;fb:req-choice url='http://anandafit.info' label='Join foursquare!' /&gt;" type="foursquare" invite="true" method="POST" action="http://anandafit.info">
                                <fb:multi-friend-selector showborder="false" cols="5" rows="3" exclude_ids="721781462" actiontext="Invite your friends to foursquare."></fb:multi-friend-selector>
                            </fb:request-form>
                        </fb:else>
                    </fb:is-logged-out>
 
            </fb:fbml>
        </script>
    </fb:serverFbml>
</body>
</html>
	<?php
}
?>

</body>
</html>
<?php ob_flush(); ?>